package com.castle.fortress.admin.flowable.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.castle.fortress.admin.core.annotation.CastleLog;
import com.castle.fortress.admin.core.constants.GlobalConstants;
import com.castle.fortress.admin.flowable.dto.FlowableAppDto;
import com.castle.fortress.admin.flowable.dto.FlowableTemplateDto;
import com.castle.fortress.admin.flowable.entity.FlowableTemplateEntity;
import com.castle.fortress.admin.flowable.form.service.FlowableFormConfigService;
import com.castle.fortress.admin.flowable.service.FlowableAppService;
import com.castle.fortress.admin.flowable.service.FlowableManageService;
import com.castle.fortress.admin.flowable.service.FlowableTemplateService;
import com.castle.fortress.admin.utils.ExcelUtils;
import com.castle.fortress.common.entity.DynamicExcelEntity;
import com.castle.fortress.common.entity.RespBody;
import com.castle.fortress.common.enums.OperationTypeEnum;
import com.castle.fortress.common.enums.YesNoEnum;
import com.castle.fortress.common.exception.BizException;
import com.castle.fortress.common.respcode.BizErrorCode;
import com.castle.fortress.common.respcode.GlobalRespCode;
import com.castle.fortress.common.utils.ConvertUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 流程模板管理表 控制器
 *
 * @author castle
 * @since 2022-09-26
 */
@Api(tags="流程模板管理表管理控制器")
@Controller
public class FlowableTemplateController {
    @Autowired
    private FlowableTemplateService flowableTemplateService;
    @Autowired
    private FlowableManageService flowableManageService;
    @Autowired
    private FlowableFormConfigService flowableFormConfigService;
    @Autowired
    private FlowableAppService flowableAppService;

    /**
     * 流程模板管理表的分页展示
     * @param flowableTemplateDto 流程模板管理表实体类
     * @param current 当前页
     * @param size  每页记录数
     * @return
     */
    @CastleLog(operLocation = "流程模板管理表分页展示", operType = OperationTypeEnum.QUERY)
    @ApiOperation("流程模板管理表分页展示")
    @GetMapping("/flowable/flowableTemplate/page")
    @ResponseBody
    @RequiresPermissions("flowable:flowableTemplate:pageList")
    public RespBody<IPage<FlowableTemplateDto>> pageFlowableTemplate(FlowableTemplateDto flowableTemplateDto, @RequestParam(required = false) Integer current, @RequestParam(required = false)Integer size){
        Integer pageIndex= current==null? GlobalConstants.DEFAULT_PAGE_INDEX:current;
        Integer pageSize= size==null? GlobalConstants.DEFAULT_PAGE_SIZE:size;
        Page<FlowableTemplateDto> page = new Page(pageIndex, pageSize);
        IPage<FlowableTemplateDto> pages = flowableTemplateService.pageFlowableTemplate(page, flowableTemplateDto);

        return RespBody.data(pages);
    }

    /**
     * 流程模板管理表的列表展示
     * @param flowableTemplateDto 流程模板管理表实体类
     * @return
     */
    @CastleLog(operLocation = "流程模板管理表列表展示", operType = OperationTypeEnum.QUERY)
    @ApiOperation("流程模板管理表列表展示")
    @GetMapping("/flowable/flowableTemplate/list")
    @ResponseBody
    public RespBody<List<FlowableTemplateDto>> listFlowableTemplate(FlowableTemplateDto flowableTemplateDto){
        List<FlowableTemplateDto> list = flowableTemplateService.listFlowableTemplate(flowableTemplateDto);
        return RespBody.data(list);
    }

    /**
     * 已部署未绑定的流程
     * @return
     */
    @CastleLog(operLocation = "已部署未绑定的流程", operType = OperationTypeEnum.QUERY)
    @ApiOperation("已部署未绑定的流程")
    @GetMapping("/flowable/flowableTemplate/unbind")
    @ResponseBody
    public RespBody<List<FlowableTemplateDto>> unbindFlowableTemplate(){
        List<FlowableTemplateDto> list = flowableTemplateService.unbindFlowableTemplate();
        return RespBody.data(list);
    }

    /**
     * 流程模板管理表保存
     * @param flowableTemplateDto 流程模板管理表实体类
     * @return
     */
    @CastleLog(operLocation = "流程模板管理表保存", operType = OperationTypeEnum.INSERT)
    @ApiOperation("流程模板管理表保存")
    @PostMapping("/flowable/flowableTemplate/save")
    @ResponseBody
    @RequiresPermissions("flowable:flowableTemplate:save")
    public RespBody<String> saveFlowableTemplate(@RequestBody FlowableTemplateDto flowableTemplateDto){
        if(flowableTemplateDto == null ){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        flowableTemplateDto.setActKey(flowableTemplateService.initActKey());
        FlowableTemplateEntity flowableTemplateEntity = ConvertUtil.transformObj(flowableTemplateDto,FlowableTemplateEntity.class);
        if(flowableTemplateService.save(flowableTemplateEntity)){
            if(flowableTemplateEntity.getFormKey()!=null){
                flowableFormConfigService.updateBindStatus(flowableTemplateEntity.getFormKey(),YesNoEnum.YES.getCode());
            }
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 流程模板管理表编辑
     * @param flowableTemplateDto 流程模板管理表实体类
     * @return
     */
    @CastleLog(operLocation = "流程模板管理表编辑", operType = OperationTypeEnum.UPDATE)
    @ApiOperation("流程模板管理表编辑")
    @PostMapping("/flowable/flowableTemplate/edit")
    @ResponseBody
    @RequiresPermissions("flowable:flowableTemplate:edit")
    public RespBody<String> updateFlowableTemplate(@RequestBody FlowableTemplateDto flowableTemplateDto){
        if(flowableTemplateDto == null || flowableTemplateDto.getId() == null || flowableTemplateDto.getId().equals(0L)){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        if(flowableTemplateDto.getContextJson()==null){
            flowableTemplateDto.setContextJson("");
        }
        FlowableTemplateEntity flowableTemplateEntity = ConvertUtil.transformObj(flowableTemplateDto,FlowableTemplateEntity.class);
        if(flowableTemplateService.updateById(flowableTemplateEntity)){
            flowableTemplateService.updateXmlData(flowableTemplateEntity);
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 流程模板管理表删除
     * @param id
     * @return
     */
    @CastleLog(operLocation = "流程模板管理表删除", operType = OperationTypeEnum.DELETE)
    @ApiOperation("流程模板管理表删除")
    @PostMapping("/flowable/flowableTemplate/delete")
    @ResponseBody
    @RequiresPermissions("flowable:flowableTemplate:delete")
    public RespBody<String> deleteFlowableTemplate(@RequestParam Long id){
        if(id == null ){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        //是否绑定应用
        FlowableAppDto flowableAppDto = new FlowableAppDto();
        flowableAppDto.setFlowId(id);
        List<FlowableAppDto> list = flowableAppService.listFlowableApp(flowableAppDto);
        if(list!=null && list.size()>0){
            throw new BizException(BizErrorCode.ACT_BIND_DEL_ERROR);
        }
        if(flowableTemplateService.delById(id)) {
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }


    /**
     * 流程模板管理表批量删除
     * @param ids
     * @return
     */
    @CastleLog(operLocation = "流程模板管理表批量删除", operType = OperationTypeEnum.DELETE)
    @ApiOperation("流程模板管理表批量删除")
    @PostMapping("/flowable/flowableTemplate/deleteBatch")
    @ResponseBody
    @RequiresPermissions("flowable:flowableTemplate:deleteBatch")
    public RespBody<String> deleteFlowableTemplateBatch(@RequestBody List<Long> ids){
        if(ids == null || ids.size()<1){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        if(flowableTemplateService.removeByIds(ids)) {
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 流程模板管理表详情
     * @param id 流程模板管理表id
     * @return
     */
    @CastleLog(operLocation = "流程模板管理表批量删除", operType = OperationTypeEnum.DELETE)
    @ApiOperation("流程模板管理表详情")
    @GetMapping("/flowable/flowableTemplate/info")
    @ResponseBody
    @RequiresPermissions("flowable:flowableTemplate:info")
    public RespBody<FlowableTemplateDto> infoFlowableTemplate(@RequestParam Long id){
        if(id == null){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        return RespBody.data(flowableTemplateService.getByIdExtends(id));
    }

    /**
     * 部署流程
     * @param id 流程模板管理表id
     * @return
     */
    @CastleLog(operLocation = "部署流程", operType = OperationTypeEnum.OTHER)
    @ApiOperation("部署流程")
    @GetMapping("/flowable/flowableTemplate/deploy")
    @ResponseBody
    @RequiresPermissions("flowable:flowableTemplate:deploy")
    public RespBody<String> deploy(@RequestParam Long id){
        if(id == null){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        FlowableTemplateEntity flowableTemplateEntity = flowableTemplateService.getById(id);
        RespBody<Map<String,String>> resp = flowableManageService.deploy(flowableTemplateEntity.getActKey());
        //部署成功
        if(resp.isSuccess()){
            flowableTemplateEntity.setStatus(YesNoEnum.YES.getCode());
            flowableTemplateEntity.setDeployId(resp.getData().get("id"));
            flowableTemplateEntity.setEngineVersion(resp.getData().get("version"));
            flowableTemplateEntity.setDeployTime(new Date());
        }else{
            flowableTemplateEntity.setStatus(YesNoEnum.NO.getCode());
            flowableTemplateEntity.setDeployId(null);
            flowableTemplateEntity.setEngineVersion(null);
            flowableTemplateEntity.setDeployTime(null);
        }
        flowableTemplateService.updateById(flowableTemplateEntity);
        return RespBody.data("部署成功");
    }

	/**
     * 动态表头导出 依据展示的字段导出对应报表
     * @param dynamicExcelEntity
     * @param response
     * @throws Exception
     */

    @CastleLog(operLocation = "流程模板管理表导出", operType = OperationTypeEnum.EXPORT)
	@PostMapping("/flowable/flowableTemplate/exportDynamic")
	@ApiOperation("动态表头导出，依据展示的字段导出对应报表")
	public void exportDynamic(@RequestBody DynamicExcelEntity<FlowableTemplateDto> dynamicExcelEntity, HttpServletResponse response) throws Exception {
		List<FlowableTemplateDto> list = flowableTemplateService.listFlowableTemplate(dynamicExcelEntity.getDto());
		//字典、枚举、接口、json常量等转义后的列表数据 根据实际情况初始化该对象，null为list数据直接导出
		List<List<Object>> dataList = null;
		/**
        * 根据实际情况初始化dataList,可参照 com.castle.fortress.admin.system.controller.TmpDemoController类中方法：exportDynamic
        */
		ExcelUtils.exportDynamic(response,dynamicExcelEntity.getFileName()+".xlsx",null,list,dynamicExcelEntity.getHeaderList(),dataList);
	}


}
